<template>
  <div>
    <div class="flex align-center justify-center flex-c" v-if="loadingFlag">
      <k-loading show></k-loading>
      <span class="fz18 c666 fb ml20">正在加载中</span>
    </div>
    <div class="file-list-container" v-if="!loadingFlag">
      <div class="setting-content tootip-file-content-common">
        <div class="setting-content-grid">
          <div>
            <ul class="setting-tabs">
              <li class="setting-tab opened" :class="[categoryIndex==-1?'active fw':'']"  @click="handleLoadCategory(0,-1)">全部</li>
              <li class="setting-tab opened" v-for="(item,index) in categoryList" :class="[categoryIndex==index?'active fw':'']" @click="handleLoadCategory(item.id,index)">{{item.title}}</li>
            </ul>
          </div>
          <div class="flex align-center btn-hidden">
            <ul class="setting-tabs">
              <li class="setting-tab opened" :class="[changeIndex==0?'active fw':'']" @click="handleLoadSort(0)">最新</li>
              <li class="setting-tab updated" :class="[changeIndex==1?'active fw':'']" @click="handleLoadSort(1)">热门</li>
              <li class="setting-tab joined" v-if="userStore.isLogin" :class="[changeIndex==2?'active fw':'']" @click="handleLoadSort(2)">我的足迹</li>
              <li class="setting-tab joined" v-if="userStore.isLogin" :class="[changeIndex==3?'active fw':'']" @click="handleLoadSort(3)">我的收藏</li>
              <li class="setting-tab joined" v-if="userStore.isLogin" :class="[changeIndex==4?'active fw':'']" @click="handleLoadSort(4)">我的订阅</li>
            </ul>
            <div class="right">
              共<span class="fw ml2 mr2">{{total}}</span>条
            </div>
            <div class="flex align-items ml10">
              <input class="search-input" v-model.trim="queryParams.keyword" id="keyword" placeholder="请输入标题、分类、标签"/>
              <button class="search-button" @click="handleSearch">搜索</button>
            </div>
          </div>
        </div>
      </div>
      <div class="file-card-content">
        <div class="card-grid mb30">
          <div class="itemcard animate__fadeIn animate__animated" :class="['animate__delay-'+(num+1)+'s',item.showFlag ==0?'gray':'']"
               v-for="(item,index) in noteList" :key="index">
            <nuxt-link :href="item.showFlag==1?'/note/'+(item.chapterFlag==1?'page':'detail')+'/'+item.id:'javascript:void(0);'" :title="item.title">
              <div class="entry-media">
                <img
                    :src="item.img"
                    :alt="item.title"
                    :title="item.title"
                    class="item-pic"/>
              </div>
              <div class="entry-wrapper">
                 <span class="meta-category-dot" v-if="item.showFlag == 0">
                    <a href="javascript:void(0);" class="green">
                      <i class="dot"></i>制作中
                    </a>
                </span>
                <span v-else>
                  <span class="meta-category-dot" v-if="item.tags && item.tags.length > 0">
                    <template v-for="(tag,index) in item.tags.split(',')" :key="index">
                      <a href="javascript:void(0);">
                        <i class="dot"></i>{{tag}}
                      </a>
                    </template>
                  </span>
                  <span class="meta-category-dot" v-else>
                      <a href="javascript:void(0);">
                        <i class="dot"></i>{{item.categoryName}}
                      </a>
                  </span>
                </span>
                <h1 class="item-title">{{item.title}}</h1>
                <p class="item-desc">{{item.description}}</p>
              </div>
              <div class="entry-footer">
                <div class="entry-meta">
                  <span class="meta-date">
                    <time :datetime="formatMsgTime(item.updateTime)">
                      <i class="iconfont icon-shijian pr tp2 fz14"></i><span class="ml3 pr tp2">{{ formatMsgTime(item.updateTime) }}</span>
                    </time>
                   </span>
                  <span class="meta-views ml10 pr tp2"><i class="iconfont icon-eye"></i><span class="ml2 pr ftp2">{{item.viewcount || 0}}</span></span>
                  <span class="meta-shhop-icon pointer pr fz11 tp5" @click.prevent="handleNoteCancelBroswer(item.id,index)"  v-if="changeIndex==2"><i class="iconfont icon-shanchu4 pr fz12"></i>删除</span>
                  <span class="meta-shhop-icon pointer pr fz11 tp5" @click.prevent="handleNoteCancelFav(item.id,index)"  v-if="changeIndex==3"><i class="iconfont icon-shanchu4 pr tp2"></i>取消</span>
                </div>
              </div>
            </nuxt-link>
          </div>
        </div>
        <k-empty :show="total == 0"></k-empty>
        <div @click="handleLoadMore" v-if="total > queryParams.pageSize && queryParams.pageNo < pages" class="flex justify-center pointer">加载更多({{total || 0}})</div>
        <div v-if="total > queryParams.pageSize && queryParams.pageNo == pages" class="flex justify-center c999 mt20 mb20">没有更多了</div>
      </div>
    </div>
  </div>
</template>
<script setup>
const userStore = useStore.userState()
const noteList = ref([])
const loadingFlag = ref(false)
const categoryList = ref([])
const route = useRoute()
const changeIndex = ref(0)
const categoryIndex = ref(-1)
const total =ref(0)
const pages =ref(0)
const queryParams = reactive({
  channelId:0,
  categoryId:0,
  keyword:"",
  notetype:0,  // 基础课 2进阶课 3 实战小册 4 面试课
  pageNo:1,
  pageSize:84,
  orderNum:3 // 0 最新  1 最热 2 最后更新 3 sorted排序
})

const props = defineProps({
  channelId: {
    type: Number,
    default: 1
  },
  sorted:{
    type: Number,
    default: 3
  }
})

const handleSearch = async () => {
  if(!queryParams.keyword){
    getDom("keyword").focus()
    useMessage().info("请输入搜索关键词")
    return;
  }
  queryParams.pageNo = 1
  noteList.value = []
  handleLoadData()
}


const handleLoadData = async () => {
  queryParams.channelId = props.channelId
  loadingFlag.value = true
  const resp = await useLoadNoteApi(queryParams)
  noteList.value = noteList.value.concat(resp.data.records)
  total.value = resp.data.total
  pages.value = resp.data.pages
  loadingFlag.value = false
}

const handleLoadCategories = async ()=>{
  const resp = await useLoadNoteCategoriesApi(props.channelId)
  categoryList.value = resp.data
}


const handleLoadCategory = async (id,index)=>{
  queryParams.categoryId = id
  queryParams.pageNo = 1
  noteList.value = []
  categoryIndex.value = index
  handleLoadData()
}

// 我的足迹
const handleLoadBroswerData = async () => {
  queryParams.channelId = props.channelId
  const resp = await useFindMyNotesBroswerPageApi(queryParams)
  noteList.value = noteList.value.concat(resp.data.records)
  total.value = resp.data.total
  pages.value = resp.data.pages
}

// 我的收藏
const handleLoadFavData = async () => {
  queryParams.channelId = props.channelId
  const resp = await useFindNoteUserFavPageApi(queryParams)
  noteList.value = noteList.value.concat(resp.data.records)
  total.value = resp.data.total
  pages.value = resp.data.pages
  loadingFlag.value = false
}

// 我的订阅
const handleLoadMyData = async () => {
  queryParams.channelId = props.channelId
  const resp = await useFindMyNotePageApi(queryParams)
  noteList.value = noteList.value.concat(resp.data.records)
  total.value = resp.data.total
  pages.value = resp.data.pages
}

const handleLoadSort = (sortnum)=>{
  noteList.value = []
  queryParams.pageNo = 1
  changeIndex.value = sortnum
  queryParams.orderNum = sortnum
  if(sortnum == 2){ // 我的足迹
    queryParams.categoryId = 0
    categoryIndex.value = -2
    handleLoadBroswerData()
  }else if(sortnum == 3){ // 我的收藏
    queryParams.categoryId = 0
    categoryIndex.value = -2
    handleLoadFavData()
  }else if(sortnum == 4){ // 我的订阅
    queryParams.categoryId = 0
    categoryIndex.value = -2
    handleLoadMyData()
  }else {  // 常规课程
    categoryIndex.value = -1
    handleLoadData()
  }
}

const handleLoadMore = ()=>{
  queryParams.pageNo++
  handleLoadData()
}


//取消收藏
const  handleNoteCancelFav = (id,index) => {
  useDialog().warning({
    content: "你确定要【取消收藏】此课程吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      try {
        // 退出逻辑
        await useCancelFavNoteApi(id)
        noteList.value.splice(index,1)
        total.value --
        emits("success",total.value)
        if(noteList.value.length == 0) {
          handleLoadSort(changeIndex.value)
        }
      }catch (e) {
        useMessage().error(e.message)
      }
    },
  });
}

//删除记录
const  handleNoteCancelBroswer = (id,index) => {
  useDialog().warning({
    content: "你确定【删除记录】吗？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      try {
        // 退出逻辑
        await useRemoveNoteHitsApi(id)
        noteList.value.splice(index,1)
        total.value --
        emits("success",total.value)
        if(noteList.value.length == 0) {
          handleLoadSort(changeIndex.value)
        }
      }catch (e) {
        useMessage().error(e.message)
      }
    },
  });
}

onMounted(() => {
  queryParams.orderNum = props.sorted
  handleLoadCategories()
  if( route.hash == '#my'){
    changeIndex.value = 4
    handleLoadMyData()
  }else if (route.hash == '#fav') {
    changeIndex.value = 3
    handleLoadFavData()
  }else{
    handleLoadData()
  }
})
</script>